/*
* Copyright (C) 2020 ~ 2023 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkHttpMedia/MkWsFlvPlayer.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkEvent/MkTimer.h"
#include "MkUtil/MkLog.h"
#include "MkUtil/MkUtil.h"
#include <signal.h>

CMkTimer *g_pTimer = nullptr;
CMkEventPool* g_pPool = nullptr;
void SigHandle(int sig)
{
    if (sig == SIGINT) {
        g_pTimer->LoopBreak();
    }
};

MkVector<CMkWsFlvPlayer*> VecPlayer;
int main(int argc, char** argv)
{
#if 1
    if (argc < 3) {
        printf("%s wsUrl TestCount", argv[0]);
        return 0;
    }
    MkString WsUrl = argv[1];
    Uint32 nCount = CMkUtil::SafeAtoi(argv[2]);
#else
    MkString WsUrl = "ws://127.0.0.1/file/aa.264.flv";
    Uint32 nCount = 10;
#endif
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    //signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
    //signal(SIGPIPE, SIG_IGN);
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigprocmask(SIG_BLOCK, &set, NULL);
#endif
    MkLogChangeLevel(LOG_DEBUG);
    signal(SIGINT, SigHandle);
    CMkEventPool Pool;
    g_pPool = &Pool;
    Pool.Start(1);
    CMkTimer Timer;
    g_pTimer = &Timer;

    for (Uint32 i = 0; i < nCount; i++) {
        CMkWsFlvPlayer *pPlayer = new CMkWsFlvPlayer(Pool.GetFreeEvent(), &Timer, [](CMkTcpClient* pClient) {
            MkVector<CMkWsFlvPlayer*>::iterator it = VecPlayer.begin();
            for (; it != VecPlayer.end(); it++) {
                if (pClient == (*it)) {
                    VecPlayer.erase(it);
                    break;
                }
            }
            MkDelete(pClient);
            if (VecPlayer.empty()) {
                g_pTimer->LoopBreak();
            }
            return NoneError;
        });
        VecPlayer.push_back(pPlayer);
        pPlayer->StartMediaSource(WsUrl, [](CMkMediaSource* pMediaSource, Uint32 ErrorCode) {
            return NoneError;
        }, [](const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam) {
            return NoneError;
        });
        CMkThread::ThreadSleep(20);
    }
    Timer.Dispatch();
    Pool.Stop();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}

